package com.etlmaster.rowprocessor.utils;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.script.ScriptException;

import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;

import com.etlmaster.executor.processors.File.FileTransInfo;
import com.etlmaster.executor.processors.File.FileTransfer;
import com.etlmaster.executor.utils.DpVfsUtils;
import com.etlmaster.executor.utils.LogWriter;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class FileWriterUtil extends FileTransfer{

	private int rowNum=0;

	public FileWriterUtil(FileTransInfo filetransInfo) {
		super(filetransInfo);
		// TODO Auto-generated constructor stub
	}
	public void writeFileByLine(String row) throws IOException, ScriptException {
		String lineSeparator = System.getProperty("line.separator", "\n");
		int lineSeparatorLength = lineSeparator.length();
		int rowLength = row.length();
		bufferWriter.write(row, 0, rowLength);
		bufferWriter.write(lineSeparator, 0, lineSeparatorLength);
		transSize += rowLength + lineSeparatorLength;
		long fileSize = transSize + sourceSize;
		if(rowNum%1000==0){
			out.flush();
			writer.flush();
			bufferWriter.flush();
		}
		if (isRelocate(fileSize, rowNum)) {
			int index = fileTransInfo.getTargetVfsURI().lastIndexOf(".");
			String fileFullPath=getFileName(fileTransInfo.getTargetVfsURI(),index,counter);
			targetFile=DpVfsUtils.getInstance().resolveFile(
					fileFullPath);
			if(!targetFile.getParent().exists())
			{
				targetFile.getParent().createFolder();
			}
			targetTempFile.moveTo(targetFile);
			LogWriter.addLog("INFO", "文件输出到{} 文件大小：{}M,行数:{}", fileFullPath,
					fileSize / 1024.0 / 1024.0 + "", "" + rowNum);
			out.flush();
			writer.flush();
			bufferWriter.flush();
			closeOutStream();
			DpVfsUtils.getInstance().closeFileObject(targetTempFile);
			DpVfsUtils.getInstance().closeFileObject(targetFile);
			setUpTargetObjects(fileTransInfo.getTargetVfsURI());
			transSize = 0;
			sourceSize = 0;
			rowNum = 0;
		}
		rowNum++;
	}
	public void setUpTargetObjects(String targetVfsURI) throws FileSystemException, UnsupportedEncodingException{
		targetTempFile = DpVfsUtils.getInstance().resolveFile(
				targetVfsURI+ ".tmp");
		targetFile = DpVfsUtils.getInstance().resolveFile(
				targetVfsURI);
		if (fileTransInfo.isAppend() && targetFile.exists()
				&& targetFile.getType() == FileType.FILE) {// 如果追加写，就先把存在的目标文件先改成.tmp
			sourceSize=targetFile.getContent().getSize();
			targetFile.moveTo(targetTempFile);
		}
		out = targetTempFile.getContent().getOutputStream(
				fileTransInfo.isAppend());
		LogWriter.addLog("INFO", "目标字符集为{}",
				fileTransInfo.getTargetCharSet());
		writer = new OutputStreamWriter(out,
				fileTransInfo.getTargetCharSet());
		bufferWriter = new BufferedWriter(writer);

	}

}
